package ws.very.util.lang.macroPack
import scala.language.experimental.macros
import scala.reflect.macros.whitebox.Context

object EitherMacro {

  def e[L, R](ex: Any): Either[L, R] = macro imp[L, R]
  def imp[L: c.WeakTypeTag, R: c.WeakTypeTag](c: Context)(ex: c.Expr[Any]): c.Expr[Either[L, R]] = {
    import c.universe._
    if (c.weakTypeOf[L] <:< c.weakTypeOf[R]) {
      c.Expr[Either[L, R]](q"""
        (${ex}:Any) match{
        case t:${symbolOf[L]}=>Left(t)
        case t:${symbolOf[R]}=>Right(t)
        case t=>throw new Exception(" type Error "+t)
        }
     """)
    } else {
      c.Expr[Either[L, R]](q"""
        (${ex}:Any) match{
        case t:${symbolOf[R]}=>Right(t)
        case t:${symbolOf[L]}=>Left(t)
        case t=>throw new Exception("type Error "+t)
        }
     """)
    }
  }
}